package com.metaera.app.ui.popup;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lxj.xpopup.impl.FullScreenPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.metaera.app.MetaEraApplication;
import com.metaera.app.R;
import com.metaera.app.data.model.ArticleListResponse;
import com.metaera.app.data.network.ApiParam;
import com.metaera.app.utils.DateUtils;
import com.metaera.app.utils.ToastUtils;
import com.metaera.app.utils.image.GlideApp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import androidx.annotation.NonNull;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static android.content.Context.CLIPBOARD_SERVICE;

public class ShareCalendarPopup extends FullScreenPopupView {

    protected ArticleListResponse mArticle;

    public ShareCalendarPopup(@NonNull Context context) {
        super(context);
    }

    public ShareCalendarPopup(@NonNull Context context, ArticleListResponse article) {
        super(context);
        mArticle = article;
    }

    @Override
    protected int getImplLayoutId() {

        return R.layout.popup_share_calendar;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
       TextView tvDay =  findViewById(R.id.tv_day);
        TextView tvYearMonth =  findViewById(R.id.tv_year_month);
        TextView tvWeek =  findViewById(R.id.tv_week);
        ImageView iv_avatar =  findViewById(R.id.iv_avatar);
        TextView tv_nickname =  findViewById(R.id.tv_nickname);
        RatingBar rating_bar =  findViewById(R.id.rating_bar);
        TextView tv_content =  findViewById(R.id.tv_content);

        tv_content.setText(mArticle.getContent());
        rating_bar.setRating(mArticle.getScore());
        ArticleListResponse.Author author = mArticle.getAuthor();

        int timestamp = mArticle.getRelease_time_stamp();
        tvYearMonth.setText(DateUtils.getTime(timestamp, DateUtils.PATTERN_11));
        tvWeek.setText(DateUtils.getWeekOfTimestamp(timestamp,
                getContext().getResources().getStringArray(R.array.weeks)));
        tvDay.setText(DateUtils.getTime(timestamp, DateUtils.PATTERN_12));

        if (author != null){
            tv_nickname.setText(author.getNickname());

            GlideApp.with(iv_avatar)
                    .load(author.getAvatar_img())
                    .avatar()
                    .into(iv_avatar);
        }

        findViewById(R.id.tv_wechat).setOnClickListener(v -> share2WX());
        findViewById(R.id.tv_moments).setOnClickListener(v -> share2Friend());

        findViewById(R.id.tv_download).setOnClickListener(v -> methodRequiresTwoPermission());

        findViewById(R.id.tv_link).setOnClickListener(v -> {
            dismiss();

            ClipboardManager cm = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
            cm.setPrimaryClip(ClipData.newPlainText("Simple text", ApiParam.LINK_SHARE_5 + mArticle.getId()));
            ToastUtils.makeText("复制成功");
        });

        findViewById(R.id.button_cancel).setOnClickListener(v -> dismiss());
    }

    @Override
    protected void initPopupContent() {
        super.initPopupContent();
        ViewGroup layoutContainer = findViewById(R.id.layout_container);
        XPopupUtils.applyPopupSize(
                layoutContainer,
                (int) (XPopupUtils.getAppWidth(getContext()) * 0.85f),
                getMaxHeight(),
                getPopupWidth(),
                getPopupHeight(),
                null
        );
    }

    public final int RC_CAMERA_AND_LOCATION = 1; // requestCode

    @AfterPermissionGranted(RC_CAMERA_AND_LOCATION)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            new Thread(() -> {
                String path = saveImageToGallery(getContext(), saveImage());
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(getContext(), "图片保存至" + path, Toast.LENGTH_SHORT).show());
            }).start();

            dismiss();
        } else {

            EasyPermissions.requestPermissions(getActivity(), "申请获取存储权限", RC_CAMERA_AND_LOCATION, perms);
        }
    }

    private Bitmap saveImage() {
        // 生成bitmap
        View v = findViewById(R.id.layout_container);
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.parseColor("#000988"));
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

    // 保存相册到相册
    public String saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        String fileName = context.getResources().getString(R.string.app_name);
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        String imageName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, imageName);
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(currentFile.getPath()))));

        return currentFile.getPath();
    }


    // 分享至微信
    private void share2WX() {
        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
            ToastUtils.makeText("您还未安装微信客户端");

        } else {
            new Thread(() -> share2WX(SendMessageToWX.Req.WXSceneSession)).start();
        }
    }


    // 分享至朋友圈
    private void share2Friend() {
        if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
            ToastUtils.makeText("您还未安装微信客户端");

        } else {
            new Thread(() -> share2WX(SendMessageToWX.Req.WXSceneTimeline)).start();
        }

        dismiss();
    }

    // 分享到微信
    private void share2WX(int scene) {
//        try {
        // title, desc, link, image

        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        wxWebpageObject.webpageUrl = ApiParam.LINK_SHARE_5 + mArticle.getId(); // 链接
        WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
        wxMediaMessage.title = mArticle.getTitle(); // 标题
        wxMediaMessage.description = ""; // 描述

        // 图片

//            if (drawableId != 0){
        wxMediaMessage.setThumbImage(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

//            } else if (imageLink != null){
//                Bitmap thumb = BitmapFactory.decodeStream(new URL("mShareModel.imageUrl").openStream());
//                Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb, 120, 150, true);
//                ByteArrayOutputStream stream = new ByteArrayOutputStream();
//                thumbBmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//                wxMediaMessage.thumbData = stream.toByteArray(); // 图片
//                thumb.recycle();
//            }

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = scene;
        req.message = wxMediaMessage;
        req.transaction = String.valueOf(System.currentTimeMillis());
        MetaEraApplication.sWxApi.sendReq(req);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            dismiss();
//        }
    }
}
